# -*- coding: UTF-8 -*-
import requests
import urllib
import os
import sys
import time
import threading
import Queue


# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadName, time.ctime(time.time()))


class myThread(threading.Thread):
    def __init__(self, threadID, name, a_list):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.list = a_list

    def run(self):
        print '\nstarting----'+self.name
        threadLock.acquire(1)
        unTransItem = getUnTransItem(self.list)
        threadLock.release()
        if unTransItem:
            doTrans(self,unTransItem)
            print '\nend'+self.name
        else:
            print '\nfinish'


def doTrans(thread,item):
    if item and item.keys():
        key = item.keys()[0]
        time.sleep(3)
        item[key] = 1
        thread.run()


def getUnTransItem(alist):
    for item in alist:
        if item.values() and item.values()[0] == -1:
            key = item.keys()[0]
            print '\ntrans '+key
            item[key] = 0
            return item
        else:
            continue
    return None
a_list = [
    {'1111': -1},
    {'2222': -1},
    {'3333': -1},
    {'4444': -1},
]
threadLock = threading.Lock()
thread1 = myThread(1, 'thread-1', a_list)
thread2 = myThread(2, 'thread-2', a_list)
thread1.start()
thread2.start()
# 添加线程到线程列表
threads = []
threads.append(thread1)
threads.append(thread2)
def doResolve():
    for t in threads:
        t.join()
    print "Exiting Main Thread"


def main():
    print '\n----main fun ------'

    try:
        doResolve()
    except:
        print "Error: unable to start thread"


if __name__ == "__main__":
    main()
    print '\n------thead study-----'
